package com.limao.push;

import java.util.ArrayList;
import java.util.List;

import com.alibaba.fastjson.JSON;
import com.limao.Admin.DBProvider.AdminSysMessProvider;
import com.limao.Admin.DataClass.AdminSysMessClass;
import com.limao.DBDataClass.SysCidDataClass;
import com.limao.Tool.Base64Encoder;
import com.limao.Tool.CacheClass;
import com.gexin.rp.sdk.base.IPushResult;
import com.gexin.rp.sdk.base.impl.AppMessage;
import com.gexin.rp.sdk.base.impl.ListMessage;
import com.gexin.rp.sdk.base.impl.SingleMessage;
import com.gexin.rp.sdk.base.impl.Target;
import com.gexin.rp.sdk.base.payload.APNPayload;
import com.gexin.rp.sdk.exceptions.RequestException;
import com.gexin.rp.sdk.http.IGtPush;
import com.gexin.rp.sdk.template.TransmissionTemplate;

//个推 推送
public class pushtoAPP  extends Thread {
	
	private static int SysMessId;
	
	static int numMax=20000; //每秒最大发送数量
	static int num=0;
	static int wait=1;
	static long time=0;
	
	static String appId = "cIAhbXfFti5bf4XaQ8giy2";  //众筹
	static String appkey = "YtDlzeWUxU5khC4n5HqFo";
	static String master = "AeWqsYtse98SmeaeRj01E6";
	static String host = "http://sdk.open.api.igexin.com/apiex.htm";
	
	private String title;
	private AdminSysMessClass tmp;
	private String CID;
	private ArrayList<SysCidDataClass> CIDist;
	private PushTypeEnum2 pushType;
	
	@Override
	public void run() {
		try {
			switch(pushType)
			{
			case toAPP:
				PushIoApp(title,tmp);
				break;
			case toUser:
				PushToUser(CIDist,title,tmp);
				break;
			case toUserList:
				PushToUserList(CIDist,title,tmp);
				break;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	
	public pushtoAPP(String title,AdminSysMessClass tmp) {
		super();
		SysMessId=-1;
		this.title=title;
		this.tmp = tmp;
		this.pushType=PushTypeEnum2.toAPP;

	}
	
	public pushtoAPP(ArrayList<SysCidDataClass> CIDist,String title,AdminSysMessClass tmp) {
		super();
		SysMessId=-1;
		this.title=title;
		this.tmp = tmp;
		this.CIDist=CIDist;
		this.pushType=PushTypeEnum2.toUser;
	}
	
	public pushtoAPP(ArrayList<SysCidDataClass> CIDist,String title,AdminSysMessClass tmp,boolean flag) {
		super();
		SysMessId=-1;
		this.title=title;
		this.tmp = tmp;
		this.CIDist=CIDist;
		this.pushType=PushTypeEnum2.toUserList;
	}	
	
	
	
	
	public int getSysMessId() {
		return SysMessId;
	}

	public void setSysMessId(int sysMessId) {
		SysMessId = sysMessId;
	}

	private static boolean getIsCan(int n)
	{
			
		if(CacheClass.getTime()-time>wait*1000) {
			num=0;
			wait=1;
			time=CacheClass.getTime();
		}

		
		if((num+n)<numMax)
		{
			num=num+n;
			wait=1+ n/numMax ;
			return true;
		}
		else 
			return false;
	}
	
	
	// 推送所有APP用户
	private void PushIoApp(String title,AdminSysMessClass tmp)	 {
		
		tmp.userid="0";
		String msg=JSON.toJSONString(tmp);
		msg=Base64Encoder.encode(msg);
		
		
		TransmissionTemplate template=TransmissionTemplateDemo(title,msg);
		IGtPush push = new IGtPush(host, appkey, master);
		
		AppMessage message = new AppMessage();
		message.setData(template);

		message.setOffline(true);
		message.setOfflineExpireTime(24 * 1000 * 3600);

		List<String> appIdList = new ArrayList<String>();

		appIdList.add(appId);
		message.setAppIdList(appIdList);

		try {

			IPushResult ret = push.pushMessageToApp(message,"任务别名_toApp");
			System.out.println(ret.getResponse().toString());
			if(SysMessId>0)
				AdminSysMessProvider.UpdateSysMessState(SysMessId,2);
			
		} catch (RequestException e) {
			String requstId = e.getRequestId();
			System.out.println("异常：" + requstId);
			if(SysMessId>0)
				AdminSysMessProvider.UpdateSysMessState(SysMessId,1);
		}
		


	}
	
	// 单个用户推送
	private static void PushToUser(ArrayList<SysCidDataClass> CIDList,String title,AdminSysMessClass tmp) {

		if(CIDList==null || CIDList.size()<1)
		{ 
			AdminSysMessProvider.UpdateSysMessState(SysMessId,1);
			return;
		}
		IGtPush push = new IGtPush(host,appkey, master);
		Target target1 ;
		
		for(SysCidDataClass obj:CIDList){
			
			tmp.userid=obj.userid;
			String msg=JSON.toJSONString(tmp);
			msg=Base64Encoder.encode(msg);
			
			TransmissionTemplate template=TransmissionTemplateDemo(title,msg);
			
			SingleMessage message = new SingleMessage();
			message.setOffline(true);
			message.setOfflineExpireTime(24 * 1000 * 3600);
			message.setData(template);
			
			target1 = new Target();
			target1.setAppId(appId);
			target1.setClientId(obj.cid);
	  		try {
				IPushResult ret = push.pushMessageToSingle(message, target1);
				System.out.println("正常：" + ret.getResponse().toString());
				if(SysMessId>0)
					AdminSysMessProvider.UpdateSysMessState(SysMessId,2);
				
			} catch (RequestException e) {
				String requstId = e.getRequestId();
				System.out.println("异常：" + requstId);
				if(SysMessId>0)
					AdminSysMessProvider.UpdateSysMessState(SysMessId,1);
			}
		}

	}
	
	
	////指定多用户推送
	private static void PushToUserList(ArrayList<SysCidDataClass> CIDist,String title,AdminSysMessClass tmp)	 {

		tmp.userid="0";
		String msg=JSON.toJSONString(tmp);
		msg=Base64Encoder.encode(msg);
		
		TransmissionTemplate template=TransmissionTemplateDemo(title,msg);
		final IGtPush push = new IGtPush(host, appkey, master);
		ListMessage message = new ListMessage();
		message.setData(template);
	/*		
		message.setOffline(false);
		message.setOfflineExpireTime(1000);
	*/	
		message.setOffline(true);
		message.setOfflineExpireTime(1000*3600*24);
		
		List<Target> targets = new ArrayList<Target>();
		
		for(SysCidDataClass obj:CIDist){
			Target target = new Target();
			target.setAppId(appId);
			target.setClientId(obj.cid);
			targets.add(target);
		}

		try {

			String taskId = push.getContentId(message, "任务别名_LIST");
			IPushResult ret = push.pushMessageToList(taskId, targets);
			System.out.println(ret.getResponse().toString());
			if(SysMessId>0)
				AdminSysMessProvider.UpdateSysMessState(SysMessId,2);
		} catch (RequestException e) {
			String requstId = e.getRequestId();
			System.out.println("异常：" + requstId);
			if(SysMessId>0)
				AdminSysMessProvider.UpdateSysMessState(SysMessId,1);
		}
		

	}
	
	

	private static TransmissionTemplate TransmissionTemplateDemo(String title,String msg) 
	{
		TransmissionTemplate template = new TransmissionTemplate();
		
		template.setAppId(appId); //设定接收的应用
		template.setAppkey(appkey); //用于鉴定身份是否合法
		template.setTransmissionType(2); //收到消息是否立即启动应用，1为立即启动，2则广播等待客户端自启动
		template.setTransmissionContent(msg);//透传消息内容，不支持转义字符
//      setBadge		应用icon上显示的数字
//		setContentAvailable		推送直接带有透传数据
//		setSound		通知铃声文件名
//		setCategory		在客户端通知栏触发特定的action和button显示
//		addCustomMsg		增加自定义的数据
		
		try {
			template.setPushInfo("actionLocKey", 3, "message", "sound", "payload","locKey", "locArgs", "launchImage");
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} //当iOS用户不在线时会自动使用该字段的信息
		
		APNPayload payload = new APNPayload();
	    payload.setBadge(1); //应用icon上显示的数字
	    payload.setContentAvailable(1); //推送直接带有透传数据
	    payload.setSound("default");  //通知铃声文件名
	    payload.setCategory("$由客户端定义"); //通知铃声文件名
	    //字符串模式
	    payload.setAlertMsg(new APNPayload.SimpleAlertMsg(title));
	    payload.addCustomMsg("IOSKEY", msg);
	    //字典模式使用下者
	    //payload.setAlertMsg(getDictionaryAlertMsg());
	    template.setAPNInfo(payload);//当iOS用户不在线时会自动使用该字段的信息
	    
		return template;
	}
	
	
	private static APNPayload.DictionaryAlertMsg getDictionaryAlertMsg(){
	    APNPayload.DictionaryAlertMsg alertMsg = new APNPayload.DictionaryAlertMsg();
	    alertMsg.setBody("body"); //通知文本消息字符串
	    alertMsg.setActionLocKey("ActionLockey"); //指定执行按钮所使用的Localizable.strings
	    alertMsg.setLocKey("LocKey"); //指定Localizable.strings文件中相应的key
	    alertMsg.addLocArg("loc-args"); //如果loc-key中使用的占位符，则在loc-args中指定各参数
	    alertMsg.setLaunchImage("launch-image"); //指定启动界面图片名
	    // IOS8.2以上版本支持
	    alertMsg.setTitle("Title"); //通知标题
	    alertMsg.setTitleLocKey("TitleLocKey"); //对于标题指定执行按钮所使用的Localizable.strings,仅支持IOS8.2以上版本
	    alertMsg.addTitleLocArg("TitleLocArg");//对于标题, 如果loc-key中使用的占位符，则在loc-args中指定各参数,仅支持IOS8.2以上版本
	    return alertMsg;
	}
	
	
	
	
}
